package cn.csq.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws Exception {

        ExecutorService service = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("server start...");
        while (true) {
            //accept & and 都会阻塞
            final Socket socket = serverSocket.accept();
            service.execute(
                    () -> {
                        // ... do something inside runnable task
                        try {
                            OutputStream outputStream = socket.getOutputStream();
                            outputStream.write("hello".getBytes(StandardCharsets.UTF_8));
                            byte[] bytes = new byte[1024];
                            InputStream inputStream = socket.getInputStream();
                            while (true) {
                                int read = inputStream.read(bytes);
                                if (read != -1) {
                                    System.out.println(new String(bytes,0,read));
                                }else {
                                    break;
                                }
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    });
            service.shutdown();
        }
    }
}
